package com.choudou5.solr.framework.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.NumberUtil;
import com.choudou5.solr.framework.bean.BetweenBean;
import com.choudou5.solr.util.DateUtil;
import com.choudou5.solr.util.JsonUtil;
import com.choudou5.solr.util.StrUtil;
import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Name：RequestUtil 说明
 * @@author choudou5
 * @@date 2018-07-14
 */
public class RequestUtil {

    public static String getReqUrl(HttpServletRequest req) {
        if( req.getPathInfo() != null ) {
            return req.getServletPath() + req.getPathInfo();
        }else{
            return req.getServletPath();
        }
    }


    /**
     * 判断是否为搜索引擎
     * @param req
     * @return
     */
    public static boolean isRobot(HttpServletRequest req){
        String ua = req.getHeader("user-agent");
        if(StrUtil.isBlank(ua)) return false;
        return (ua != null
                && (ua.indexOf("Baiduspider") != -1 || ua.indexOf("Googlebot") != -1
                || ua.indexOf("sogou") != -1
                || ua.indexOf("sina") != -1
                || ua.indexOf("iaskspider") != -1
                || ua.indexOf("ia_archiver") != -1
                || ua.indexOf("Sosospider") != -1
                || ua.indexOf("YoudaoBot") != -1
                || ua.indexOf("yahoo") != -1
                || ua.indexOf("yodao") != -1
                || ua.indexOf("MSNBot") != -1
                || ua.indexOf("spider") != -1
                || ua.indexOf("Twiceler") != -1
                || ua.indexOf("Sosoimagespider") != -1
                || ua.indexOf("naver.com/robots") != -1
                || ua.indexOf("Nutch") != -1
                || ua.indexOf("spider") != -1));
    }

    public static String getHeader(HttpServletRequest request, String name) {
        String header = request.getHeader(name);
        return header;
    }

    public static void setHeader(HttpServletResponse response, String name, String value) {
        response.setHeader(name, value);
    }

    /**
     *  获取request中参数
     * @param request 页面请求
     */
    public static Map<String, Object> getRequestParameters(HttpServletRequest request) {
        if("GET".equals(request.getMethod())){//GET请求时的参数
            String urlParameter = request.getQueryString();//网址中的参数
            if(urlParameter!=null && !"".equals(urlParameter)){
                Map<String, Object> map = new HashMap<String, Object>(10);
                try {
                    urlParameter = URLDecoder.decode(urlParameter, "UTF-8");

                    String[] arr = urlParameter.split("&");
                    for (int i = 0; i <arr.length; i++) {
                        int eqDex = arr[i].indexOf("=");
                        String key = arr[i].substring(0, eqDex);
                        String value = arr[i].substring( eqDex+1);
                        map.put(key, value);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return map;
            }
            return new HashMap<>(1);
        }else if("POST".equals(request.getMethod())){//POST请求时的参数
            //得到request对象中用来封装数据的Map集合
            return request.getParameterMap();
        }
        return new HashMap<>(1);
    }



    public static Short getShortParameter(HttpServletRequest request, String paramName) {
        String id = request.getParameter(paramName);
        if (StrUtil.isNotBlank(id)) {
            try {
                return new Short(id);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    public static Integer getIntParameter(HttpServletRequest request, String paramName) {
        return getIntParameter(request, paramName, null);
    }

    public static Integer getIntParameter(HttpServletRequest request, String paramName, Integer defVal) {
        String id = request.getParameter(paramName);
        if (StrUtil.isNotBlank(id)) {
            try {
                return new Integer(id);
            } catch (Exception e) {
                return defVal;
            }
        }
        return defVal;
    }


    public static List<Integer> getIntParameterList(HttpServletRequest request, String paramName) {
        List<Integer> list = new ArrayList<Integer>(5);
        String[] strInts = request.getParameterValues(paramName + "[]");
        if(ArrayUtil.isNotEmpty(strInts)){
            for(String strInt:strInts){
                list.add(Integer.valueOf(strInt));
            }
        }
        return list;
    }


    public static BigDecimal getBigDecimalParameter(HttpServletRequest request, String paramName) {
        String id = request.getParameter(paramName);
        if (StrUtil.isNotBlank(id)) {
            try {
                return new BigDecimal(id);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }


    public static Date getDateParameter(HttpServletRequest request, String paramName) {
        String dateString = request.getParameter(paramName);
        if (StrUtil.isNotEmpty(dateString)) {
            try {
                return DateUtil.parseDate(dateString);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    public static BetweenBean getRangeDateParameter(HttpServletRequest request, String paramName) {
        return getRangeDateParameter(request, paramName, " - ");
    }

    public static BetweenBean getRangeDateParameter(HttpServletRequest request, String paramName, String separator) {
        String dateStr = request.getParameter(paramName);
        if (StrUtil.isNotEmpty(dateStr)) {
            try {
                String[] array = dateStr.split(separator);
                if(array.length == 2){
                    return new BetweenBean(DateUtil.parse(array[0]), DateUtil.parse(array[1]));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取 范围字符串 （为防注入 日期请使用 getRangeDateParameter）
     * @param request
     * @param paramName
     * @param separator
     * @return
     */
    public static BetweenBean getRangeStrParameter(HttpServletRequest request, String paramName, String separator) {
        String dateStr = request.getParameter(paramName);
        if (StrUtil.isNotEmpty(dateStr)) {
            try {
                String[] array = dateStr.split(separator);
                if(array.length == 2){
                    return new BetweenBean(array[0], array[1]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean getBooleanParameter(HttpServletRequest request,String paramName){
        String paramValue = request.getParameter(paramName);
        try{
            if(StrUtil.isNotEmpty(paramValue)){
                if(paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("Y") || paramValue.equalsIgnoreCase("1")){
                    return true;
                }
            }
        }catch (Exception e) {
        }
        return false;
    }
    /**
     * 获取 Boolean 参数
     * @param request
     * @param paramName
     * @param defVal
     * @return
     */
    public static Boolean getBoolParameter(HttpServletRequest request,String paramName, Boolean defVal){
        String paramValue = request.getParameter(paramName);
        try{
            return Boolean.valueOf(paramValue);
        }catch (Exception e) {
            return defVal;
        }
    }


    public static String getStrParameter(HttpServletRequest request, String paramName) {
        return getStrParameter(request, paramName, null);
    }

    public static String getStrParameterUnescapeJava(HttpServletRequest request, String paramName) {
        String str = getStrParameter(request, paramName, null);
        if(StrUtil.isNotBlank(str)){
            return StringEscapeUtils.unescapeJava(str);
        }
        return null;
    }


    public static String getStrParameter(HttpServletRequest request, String paramName, String defaultValue) {
        String ret = request.getParameter(paramName);
        if(StrUtil.isEmpty(ret))
            return defaultValue;
        if(ret.startsWith("%")){
            return EscapeUtil.unescape(ret);
        }
        return ret;
    }

    public static String[] getStrParameters(HttpServletRequest request, String paramName) {
        String[] strValues = request.getParameterValues(paramName + "[]");
        if(strValues == null)
            strValues = request.getParameterValues(paramName);
        if(strValues == null)
            strValues = new String[]{};
        return strValues;
    }

    public static String[] getStrParameters(HttpServletRequest request, String paramName, String separator) {
        String strValue = request.getParameter(paramName);
        if(strValue != null)
            return strValue.split(separator);
        return null;
    }

    public static List<String> getStrParameterList(HttpServletRequest request, String paramName) {
        List<String> list = new ArrayList<String>(5);
        String[] strs = request.getParameterValues(paramName + "[]");
        if(ArrayUtil.isNotEmpty(strs)){
            for(String id:strs){
                list.add(id);
            }
        }
        return list;
    }

    public static List<String> getStrParameterList(HttpServletRequest request, String paramName, String separator) {
        List<String> list = new ArrayList<String>(5);
        String str = getStrParameter(request, paramName);
        if(StrUtil.isBlank(str))
            return list;
        String[] strs = str.split(separator);
        if(ArrayUtil.isNotEmpty(strs)){
            for(String id:strs){
                list.add(id);
            }
        }
        return list;
    }


    public static Long getLongParameter(HttpServletRequest request,String paramName){
        String paramValue = request.getParameter(paramName);
        try{
            return Long.valueOf(paramValue);
        }catch (Exception e) {
            return null;
        }
    }

    public static Long getPhoneParameter(HttpServletRequest request,String paramName){
        String phoneStr = getStrParameter(request, paramName);
        if(StrUtil.isNotBlank(phoneStr)){
            if(phoneStr.length() == 11 && NumberUtil.isNumber(phoneStr)){
                return Long.parseLong(phoneStr);
            }
        }
        return null;
    }

    public static List<Long> getLongParameterList(HttpServletRequest request, String paramName, String separator) {
        List<Long> list = new ArrayList<Long>(5);
        String str = getStrParameter(request, paramName);
        if(StrUtil.isBlank(str))
            return list;
        String[] strLongs = str.split(separator);
        if(ArrayUtil.isNotEmpty(strLongs)){
            for(String strLong:strLongs){
                list.add(Long.valueOf(strLong));
            }
        }
        return list;
    }

    public static List<Long> getLongParameterList(HttpServletRequest request, String paramName) {
        List<Long> list = new ArrayList<Long>(5);
        Map map = request.getParameterMap();
        String[] strs = request.getParameterValues(paramName + "[]");
        if(ArrayUtil.isEmpty(strs))
            strs = request.getParameterValues(paramName);
        if(ArrayUtil.isNotEmpty(strs)){
            for(String id : strs){
                list.add(Long.valueOf(id));
            }
        }
        return list;
    }

    public static Date getParameterDateTime(HttpServletRequest request, String paramName) {
        try{
            String ret = getStrParameter(request, paramName, null);
            if (ret == null) {
                return null;
            }
            return DateUtil.parse(ret, "yyyy-MM-dd HH:mm:ss");
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static Map<String,Object> getMapRequest(final HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        for(Iterator<String> it = request.getParameterMap().keySet().iterator();it.hasNext();){
            String key = it.next();
            String[] values = request.getParameterValues(key);
            if (values != null) {
                if (values.length == 1) {
                    params.put(key, values[0]);
                } else {
                    params.put(key, values);
                }
            }
        }
        return Collections.unmodifiableMap(params);
    }

    public static Map<String, String> getMapRequest(final HttpServletRequest request, String paramName) {
        Map<String, Object> params = new HashMap<String, Object>();
        String jsonStr = getStrParameter(request, paramName, null);
        if(StrUtil.isNotBlank(jsonStr)){
            return JsonUtil.toJavaObj(jsonStr, Map.class);
        }
        return null;
    }

    /**
     * 判断请求是否是ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request){
        Enumeration<String> headerNames = request.getHeaderNames();
        String accept = request.getHeader("accept");
        if(accept != null && accept.indexOf("application/json") > -1 || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)){
            return true;
        }
        return false;
    }

}
